<template>
  <page-header-wrapper :title="false">
    <div class="Row">
      <div class="leftBlock">
        <typicalLeftTree
          ref="typicalLeftTree"
          :leftTreeConfig="leftTreeConfig"
          @select="leftTreeClick"
        ></typicalLeftTree>
      </div>
      <div class="Role rightBlock">
        <a-spin tip="加载中..." class="position" v-if="roleLoading"> </a-spin>
        <a-modal
          width="45%"
          v-model="modleVisible"
          :title="form.id ? '编辑组织机构' : '新增组织机构'"
          @cancel="() => (this.modleVisible = false)"
          :confirm-loading="formButtonDisableFlag"
          @ok="onSubmit"
        >
          <div id="modalContent">
            <div class="formAspin" v-if="editWaitForLoading">
              <a-spin />
            </div>
            <a-form-model
              ref="formRef"
              :model="form"
              :rules="rules"
              :label-col="{ span: 6 }"
              :wrapper-col="{ span: 18 }"
            >
              <a-row type="flex" justify="space-between">
                <a-col :span="12">
                  <Input :form="form" label="组织机构" prop="name" placeholder="请输入组织机构"></Input>
                </a-col>
                <!-- <a-col :span="12">
                  <Input :form="form" label="组织代码" prop="code" placeholder="请输入组织代码"></Input>
                </a-col> -->
                <a-col :span="12">
                  <Input :form="form" label="联系人" prop="contact" placeholder="请输入联系人"></Input>
                </a-col>
                <a-col :span="12">
                  <Input :form="form" label="联系电话" prop="contactPhone" placeholder="请输入联系电话"></Input>
                </a-col>
                <a-col :span="12">
                  <Input :form="form" label="邮箱" prop="email" placeholder="请输入邮箱"></Input>
                </a-col>

                <a-col :span="12">
                  <treeSelect
                    :form="form"
                    prop="parentCode"
                    label="上级组织"
                    placeholder="请选择上级组织"
                    :treeData="oDictionary.organizationsTree"
                    :disabled="isEdit"
                  ></treeSelect>
                </a-col>
                <a-col :span="12">
                  <Input :form="form" label="微信账户" prop="wechatAccount" placeholder="请输入微信账户"></Input>
                </a-col>
                <a-col :span="12">
                  <Input :form="form" label="支付宝账户" prop="alipayAccount" placeholder="请输入支付宝账户"></Input>
                </a-col>
                <a-col :span="24">
                  <a-col :span="12">
                    <Select
                      :form="form"
                      label="是否分账"
                      prop="isProfitSharing"
                      placeholder="请选择是否分账"
                      :optList="getYesNo()"
                      @change="fnProfitsharingScale"
                    ></Select>
                  </a-col>
                  <a-col :span="12" v-if="isProfitsharingScale || form.profitSharingScale">
                    <InputNumber
                      :rules="{
                        required: true,
                        message: '请输入分账比例',
                        trigger: 'blur',
                      }"
                      :form="form"
                      label="分账比例"
                      prop="profitSharingScale"
                      placeholder="请输入分账比例"
                      :max="0.5"
                      :min="0.01"
                      :precision="2"
                      :step="0.01"
                    ></InputNumber>
                  </a-col>
                </a-col>
                <!-- <a-col :span="12">
                  <Select
                    :form="form"
                    label="状态"
                    prop="isEnable"
                    placeholder="请选择状态"
                    :optList="getIsEnableOption()"
                  ></Select>
                </a-col> -->
                <a-col :span="24">
                  <Textarea
                    :label-col="{ span: 3 }"
                    :wrapper-col="{ span: 21 }"
                    :form="form"
                    label="备注"
                    prop="remark"
                    placeholder="请输入备注"
                  ></Textarea>
                </a-col>
              </a-row>
            </a-form-model>
          </div>
        </a-modal>
        <typicalSearch ref="insideSearch" :searchConfig="searchConfig" @searchMethod="getTableData"></typicalSearch>
        <div class="table">
          <div class="tableTitle">
            <div class="title">组织机构列表</div>
            <div class="addButton">
              <a-button type="primary" @click="handleEdit()"> 新增组织机构 </a-button>
            </div>
          </div>
          <div class="tableList">
            <typicalTable
              ref="insideTable"
              :tableConfig="tableConfig"
              :tableData="tableData"
              @getTableData="getTableData"
            >
              <template v-slot="slotProps">
                <Button label="编辑" @click="handleEdit(slotProps.record)"></Button>
                <a-popconfirm
                  slot="action"
                  title="此操作将删除该条数据，是否继续?"
                  ok-text="是"
                  cancel-text="否"
                  @confirm="handleDelete(slotProps.record)"
                >
                  <Button v-if="slotProps.record.isSystem !== 1" type="stop" label="删除"></Button>
                </a-popconfirm>
              </template>
            </typicalTable>
          </div>
        </div>
      </div>
    </div>
  </page-header-wrapper>
</template>
<script>
import moment from 'moment';
import typicalSearch from '@/components/typicalSearch';
import typicalTable from '@/components/typicalTable';
import typicalLeftTree from '@/components/typicalLeftTree';
import Input from '@/components/typicalControl/Input';
import InputNumber from '@/components/typicalControl/InputNumber';
import treeSelect from '@/components/typicalControl/treeSelect';
import Select from '@/components/typicalControl/select';
import Textarea from '@/components/typicalControl/textarea';
import Button from '@/components/typicalControl/button';
import { getIsEnableOption, getYesNo } from '@/utils/frequentInterface';
import { recursionTreeDisabled } from '@/utils/tool';

import {
  organizationsTree,
  listOrganizations,
  createOrganization,
  updateOrganization,
  deleteOrganizationById,
} from '@/api/system';

export default {
  name: 'UserManage',
  components: {
    typicalSearch: typicalSearch,
    typicalTable: typicalTable,
    typicalLeftTree: typicalLeftTree,
    Input: Input,
    treeSelect: treeSelect,
    Select: Select,
    InputNumber: InputNumber,
    Button: Button,
    Textarea: Textarea,
  },
  data() {
    return {
      isProfitsharingScale: false, // 是否显示分账比例
      formButtonDisableFlag: false, // 表单确定禁用按钮 防止多次点击多次保存
      editWaitForLoading: false, // 加载编辑回显数据等待Loading
      roleLoading: false, // 加载表格的loading
      modleVisible: false, // 控制弹框
      form: {
        name: undefined,
        // code: undefined,
        contact: undefined,
        contactPhone: undefined,
        email: undefined,
        parentCode: undefined,
        wechatAccount: undefined,
        alipayAccount: undefined,
        isProfitSharing: undefined,
        profitSharingScale: undefined,
        remark: undefined,
      },
      rules: {
        // 规则验证
        name: [
          { required: true, message: '请输入组织机构', trigger: 'blur' },
          { max: 15, message: '最大长度不能超过15个字', trigger: 'blur' },
        ],
        // code: [
        //   { required: true, message: '请输入组织代码', trigger: 'blur' },
        //   { max: 15, message: '最大长度不能超过15个字', trigger: 'blur' },
        // ],
        contact: [
          { required: true, message: '请输入联系人', trigger: 'blur' },
          { max: 15, message: '最大长度不能超过15个字', trigger: 'blur' },
        ],
        contactPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { max: 45, message: '最大长度不能超过45个字', trigger: 'blur' },
        ],
        wechatAccount: [
          { required: true, message: '请输入微信账户', trigger: 'blur' },
          { max: 20, message: '最大长度不能超过20个字', trigger: 'blur' },
        ],
        alipayAccount: [
          { required: true, message: '请输入支付宝账户', trigger: 'blur' },
          { max: 20, message: '最大长度不能超过20个字', trigger: 'blur' },
        ],
        parentCode: [{ required: true, message: '请选择上级组织', trigger: 'change' }],
        isProfitSharing: [{ required: true, message: '请选择是否分账', trigger: 'change' }],
      },
      permissionsTreeArray: [], // 表单的树形下拉数据
      expandedKeys: [], // 控制树形下拉 展开收起全选取消全选 功能
      checkedKeys: [], // 树形下拉选中的数据
      // 搜索组件配置
      searchConfig: {
        formItemList: [
          {
            type: 'input',
            prop: 'searchName',
            value: '',
            label: '组织机构',
          },
          {
            type: 'rangeDatePicker',
            prop: 'searchCreateDateBegin&searchCreateDateEnd',
            value: [],
            label: '创建日期',
          },
        ],
        parent: this,
      },
      // 列表组件配置
      tableConfig: {
        columns: [
          {
            title: '组织机构',
            dataIndex: 'name',
            ellipsis: true,
          },
          {
            title: '代码',
            dataIndex: 'code',
            ellipsis: true,
          },
          {
            title: '备注',
            dataIndex: 'remark',
            ellipsis: true,
          },
          {
            title: '创建时间',
            dataIndex: 'createTime',
            ellipsis: true,
            customRender: this.formatterTime,
          },
          // {
          //   title: '状态',
          //   dataIndex: 'isEnable',
          //   width: '60px',
          //   scopedSlots: { customRender: 'isEnable' }
          // },
          {
            title: '操作',
            scopedSlots: { customRender: 'action' },
          },
        ],
        pageSize: this.$store.state.user.defaultPaginationPagesize,
        pageSizeOptions: this.$store.state.user.defaultPaginationOptions,
        parent: this,
      },
      // 列表组件数据
      tableData: {
        records: [],
        total: 0,
      },
      // 详情左侧树组件
      leftTreeConfig: {
        treeData: [],
      },
      // 左侧树点击存放的组织机构id
      searchParentId: null,
      oDictionary: {
        organizationsTree: [],
      },
      isEdit: false,
    };
  },
  created() {
    this.getDictionary();
  },
  mounted() {
    this.$refs.insideSearch.searchInfo();
  },
  methods: {
    getYesNo,
    getIsEnableOption,

    /**
     * [getDictionary 获取各种字典]
     * @return {[type]} [description]
     */
    getDictionary(leftTreeUpData) {
      // 组织列表树形结构数据
      organizationsTree().then((res) => {
        if (res.code == 200) {
          let datas = res.data;
          this.leftTreeConfig.treeData = datas;

          this.searchParentId = datas.length > 0 ? datas[0].code : '';
          this.$refs.insideSearch.searchInfo();
          recursionTreeDisabled(datas);
          this.oDictionary.organizationsTree = datas;
          if (leftTreeUpData) {
            this.$nextTick(() => {
              this.$refs.typicalLeftTree.manualUpdate(true);
            });
          }
        }
      });
    },
    /**
     * [getTableData 获取表格数据]
     * @param  {[type]} searchParam [搜索条件]
     * @return {[type]}             [description]
     */
    getTableData(searchParam) {
      if (!this.searchParentId) return;
      if (this.searchParentId) searchParam.searchParentId = this.searchParentId;
      this.roleLoading = true;
      let params = {
        offset: searchParam.pageNumber ? searchParam.pageNumber + 1 : 1,
        limit: searchParam.pageSize ? searchParam.pageSize : 10,
        receiveTimeBegin: searchParam.searchCreateDateBegin,
        receiveTimeEnd: searchParam.searchCreateDateEnd,
        parentCode: this.searchParentId,
        name: searchParam.searchName,
      };
      listOrganizations(params)
        .then((res) => {
          if (res.code === 200 && res.data.records) {
            let datas = res.data;
            datas.total = Number(datas.total);
            this.tableData = datas;
          } else {
            this.tableData.records = [];
            this.tableData.total = 0;
          }
        })
        .finally(() => {
          this.roleLoading = false;
        });
    },
    /**
     * [fnProfitsharingScale 是否显示分账字段]
     * @param  {[type]} e [选项值]
     * @return {[type]}   [description]
     */
    fnProfitsharingScale(e) {
      if (e === 1) {
        this.isProfitsharingScale = true;
      } else {
        this.isProfitsharingScale = false;
      }
      this.form.profitSharingScale = undefined;
    },
    /**
     * @description: 新增编辑组织机构表单提交
     */
    onSubmit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.formButtonDisableFlag = true;
          if (this.isEdit) {
            // 20220118z 组件null后台不更新
            if (!this.form.profitSharingScale) {
              this.form.profitSharingScale = 0;
            }
            this.editRole(this.form);
          } else {
            this.roleAdd(this.form);
          }
        } else {
          return false;
        }
      });
    },

    /**
     * [initializationForm 初始化form数据]
     * @return {[type]} [description]
     */
    initializationForm() {
      this.isProfitsharingScale = false;
      var form = {
        name: undefined,
        contact: undefined,
        contactPhone: undefined,
        email: undefined,
        parentCode: undefined,
        wechatAccount: undefined,
        alipayAccount: undefined,
        isProfitSharing: undefined,
        profitSharingScale: undefined,
        remark: undefined,
      };
      // form.parentCode = this.searchParentId;
      return form;
    },

    /**
     * @description: 新增组织机构权限
     * @param {object} addRoleParam 表单参数
     */
    roleAdd(addRoleParam) {
      createOrganization(addRoleParam)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('新增成功');
            this.formSuccessOperation(res);
          }
        })
        .finally(() => {
          this.formButtonDisableFlag = false;
        });
    },

    /**
     * @description: 编辑组织机构权限
     * @param {object} editRoleParam 表单参数
     */
    editRole(editRoleParam) {
      let params = { ...this.form };
      params.id = editRoleParam.id;
      updateOrganization(params)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('编辑成功');
            this.formSuccessOperation(res);
          }
        })
        .finally(() => {
          this.formButtonDisableFlag = false;
        });
    },

    /**
     * @description: 表单新增编辑成功后的公共的代码 （消息提示 搜索框重置 请求表格数据）
     * @param {object} successFormData 表单请求成功后返回的对象
     */
    formSuccessOperation(successFormData) {
      this.modleVisible = false;
      this.$refs.insideTable.updateListData();
      this.getDictionary(true);
    },

    /**
     * [handleEdit 新增或编辑]
     * @param  {[type]} row [如果编辑入参行数据]
     * @return {[type]}     [description]
     */
    handleEdit(row) {
      this.isEdit = false;
      this.modleVisible = true;
      this.form = this.initializationForm();
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
      if (row) {
        this.isEdit = true;
        this.form = { ...row };

        this.form.parentCode = row.parentCodeId;
      }
    },

    /**
     * @description: 点击删除
     * @param {object} roleTableRowData 格某一行的数据对象
     */
    handleDelete(roleTableRowData) {
      deleteOrganizationById(roleTableRowData.id).then((res) => {
        if (res.code == 200) {
          this.$message.success('删除成功');
          this.$refs.insideTable.updateListData();
          this.getDictionary(true);
        }
      });
    },
    formatterTime(val) {
      return val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : '';
    },
    leftTreeClick(val) {
      this.searchParentId = val.code;
      this.$refs.insideSearch.searchInfo();
    },
  },
};
</script>

<style lang="less" scoped>
.Role {
  width: 100%;
  height: calc(100vh - 150px);
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  position: relative;
  .position {
    width: 100%;
    height: 100%;
    background: white;
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
  }
  .table {
    flex: 1;
    background: white;
    border-radius: 5px;
    display: flex;
    flex-direction: column;
    .tableTitle {
      width: 100%;
      height: 64px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #ececec;
      padding: 0 20px;
      margin-bottom: 10px;
      .title {
        width: 80%;
        height: 100%;
        display: flex;
        align-items: center;
        font-size: 18px;
        font-weight: 550;
      }
      .addButton {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
    }
    .tableList {
      // max-height: calc(100vh - 380px);
      // overflow: auto;
      /deep/ .tableScroll {
        max-height: calc(100vh - 380px);
        overflow: auto;
      }
    }
  }
}
#modalContent {
  width: 100%;
  height: 450px;
  overflow: auto;
  position: relative;
  .formAspin {
    position: absolute;
    width: 100%;
    height: 450px;
    background: #ececec;
    border-radius: 4px;
    z-index: 999;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.Row {
  overflow: hidden;
}
.leftBlock {
  width: 300px;
  height: calc(100vh - 150px);
  float: left;
  background: #fff;
  padding-top: 10px;
}
.rightBlock {
  float: right;
  width: calc(100% - 310px);
}
/deep/ .ant-input {
  padding: 4px 6px;
}

/deep/ .searchForm .ant-col-6{
  width: 35%;
}
/deep/ .searchForm .ant-col-4,/deep/ .searchForm .ant-col-12{
  width: 25%;
}

</style>
